package controllers

import "LoginTemplate/models"

type ShopController struct {
	BaseController
}

type Shop struct {
	Id          int    `json:"id"`
	ShopName    string `json:"shop_name"`
	ShopAddress string `json:"shop_address"`
	ShopPhone   string `json:"shop_phone"`
}

// 添加门店
func (u *ShopController) InsertShop() {
	var shop Shop
	err := u.ShouldBind(&shop)
	if err != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "insert into shop ( shop_name,shop_address, shop_phone) values ( ? ,? ,? )"
	tx := models.DB.Debug().Exec(sql, shop.ShopName, shop.ShopAddress, shop.ShopPhone)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

// 修改门店
func (u *ShopController) UpdateShop() {
	var shop Shop
	err := u.ShouldBind(&shop)
	if err != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "update shop set shop_name = ?,shop_address = ?,  shop_phone = ? where id = ?"
	tx := models.DB.Debug().Exec(sql, shop.ShopName, shop.ShopAddress, shop.ShopPhone, shop.Id)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

// 删除门店
func (u *ShopController) DeleteShop() {
	var shop Shop
	err := u.ShouldBind(&shop)
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	sql := "delete from shop where id = ?"
	tx := models.DB.Debug().Exec(sql, shop.Id)
	if tx.Error != nil {
		u.JsonMsg(500, "", "失败")
	}
	u.JsonMsg(200, "", "成功")
}

type ShopData struct {
	Code        int    `json:"code"`
	Msg         string `json:"msg"`
	Data        []Shop `json:"data"`
	Sum         int    `json:"sum"`         //总页数
	CurrentPage int    `json:"currentPage"` //当前页
	TotalNumber int    `json:"totalNumber"` //总条数
}

// 查询门店
func (u *ShopController) SelectShop() {
	var pictureList PictureList
	err := u.ShouldBind(&pictureList)
	var sum int
	var totalNumber int
	if err != nil {
		println(err.Error())
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var shop []Shop
	sql := "select * from shop limit ? , ?"
	tx := models.DB.Debug().Raw(sql, (pictureList.Page-1)*pictureList.Size, pictureList.Size).Scan(&shop)
	sqlsum := "SELECT CEIL(COUNT(*) / ? ) FROM shop"
	models.DB.Debug().Raw(sqlsum, pictureList.Size).Scan(&sum)
	sqlNumBer := "select count(*) from shop"
	models.DB.Debug().Raw(sqlNumBer).Scan(&totalNumber)
	if tx.Error != nil {
		u.JsonMsg(500, "", "请求异常，请稍候再试")
	}
	var picturedata ShopData
	picturedata.Code = 200
	picturedata.Data = shop
	picturedata.Msg = "成功"
	picturedata.Sum = sum
	picturedata.CurrentPage = pictureList.Page
	picturedata.TotalNumber = totalNumber
	//return picturedata
	u.JsonMsg(200, map[string]interface{}{
		"list":  picturedata,
		"count": "",
	}, "success")
}
